
// 对用户路径切换进行劫持
import { reroute } from './reroute.js';

function urlRoute() {
    // console.log('hashchange--变化',);
    reroute(arguments)
}

function urlRoute1() {
        // console.log('popstate--变化',);
    reroute(arguments)
}
window.addEventListener('hashchange', urlRoute)

window.addEventListener('popstate', urlRoute1) // 浏览器前进后退会执行的方法

const captureEventListeners = {
    hashchange: [],
    popstate: []
}

const listeningEvents = ['hashchange', 'popstate']
const originAddEventListener = window.addEventListener
const originRemoveEventListener = window.removeEventListener

window.addEventListener = function (eventName, callback) {
    // 如果是 hashchange 或 popstate 事件，并且回调函数不在 captureEventListeners 中/
    if (listeningEvents.includes(eventName) && !captureEventListeners[eventName].some(fn => fn === callback)) {
        return captureEventListeners[eventName].push(callback);
    }

    return originAddEventListener.apply(this, arguments);

}


window.removeEventListener = function (eventName, callback) {
    // 如果是 hashchange 或 popstate 事件，并且回调函数在 captureEventListeners 中
    if (listeningEvents.includes(eventName)) {
        captureEventListeners[eventName] = captureEventListeners[eventName].filter(fn => fn !== callback);
        return
    }

    return originRemoveEventListener.apply(this, arguments);
}

// 调用捕获的事件监听器
export function callCaptureEventListeners(e) {
    if (e) {

        const eventType = e[0].type;
        if (listeningEvents.includes(eventType)) {

            captureEventListeners[eventType].forEach(callback => {
                callback.apply(this, e);
            });


        }
    }

}

//
window.history.pushState = patchFn(window.history.pushState, 'pushState')
window.history.replaceState = patchFn(window.history.replaceState, 'replaceState')
function patchFn(fn, type) {
    return function () {
       const oldUrl=window.location.href;
        const result = fn.apply(this, arguments);
        const newUrl = window.location.href;

        // 如果 URL 发生变化，触发相应的事件
        if (oldUrl !== newUrl) {
           window.dispatchEvent(new PointerEvent('popstate'))
        }
        return result;
    }
}